#!/usr/bin/env python3
"""
调试版本的视频拆分器
"""

import asyncio
from pathlib import Path
from app.services.video_splitter import VideoSplitter
import logging

# 设置详细日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

async def debug_video_split():
    """调试视频拆分问题"""
    
    video_path = Path("uploads/90e15f07-59de-4250-b611-f1cbc6940acc.mp4")
    
    if not video_path.exists():
        print(f"❌ 视频文件不存在: {video_path}")
        return
    
    print(f"🧪 调试视频拆分")
    print(f"📹 视频文件: {video_path}")
    
    splitter = VideoSplitter()
    
    try:
        # 1. 获取视频信息
        print(f"\n1️⃣ 获取视频信息...")
        video_info = await splitter._get_video_info(video_path)
        print(f"   视频时长: {video_info['duration']:.1f}秒")
        print(f"   视频分辨率: {video_info['width']}x{video_info['height']}")
        
        # 2. 测试单个片段提取
        print(f"\n2️⃣ 测试单个片段提取...")
        
        # 创建输出目录
        video_id = video_path.stem
        segment_dir = Path("uploads/segments") / video_id
        segment_dir.mkdir(parents=True, exist_ok=True)
        
        # 测试提取第一个片段
        segment_path = segment_dir / "debug_segment_000.mp4"
        
        print(f"   输出路径: {segment_path}")
        
        # 手动调用_extract_segment方法
        success = await splitter._extract_segment(
            video_path, segment_path, 0.0, 60.0
        )
        
        print(f"   提取结果: {'✅ 成功' if success else '❌ 失败'}")
        
        if success and segment_path.exists():
            file_size = segment_path.stat().st_size
            print(f"   文件大小: {file_size} bytes")
        
        # 3. 测试完整拆分流程（只拆分前3个片段）
        print(f"\n3️⃣ 测试完整拆分流程...")
        
        # 修改拆分参数，只生成3个片段进行测试
        result = await splitter.split_video_by_duration(
            video_path, 
            segment_duration=60,
            max_segments=3,  # 只测试3个片段
            min_segment_duration=10
        )
        
        print(f"   拆分结果:")
        print(f"     需要拆分: {result.get('need_split')}")
        print(f"     片段数量: {len(result.get('segments', []))}")
        
        if result.get('segments'):
            for i, segment in enumerate(result['segments'][:3]):
                print(f"     片段{i+1}: {segment['filename']} ({segment.get('duration', 0):.1f}s)")
        
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(debug_video_split())